<?php
/**
 * Note: *
 * Date: 2021/7/12
 */
namespace App\Http\Controllers\Admin;

use App\Caches\Game\AppVersionCache;
use App\Models\Game\Center\AppVersion;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Contracts\Routing\ResponseFactory;
use Illuminate\Http\Request;
use Illuminate\Http\Response;

class AppVersionController extends CurdController
{
    protected string $classModel = AppVersion::class;

    protected array $searchFields = [
        'appid',
        'source',
        'os',
        'curVer',
    ];

    /**
     * 保存之前
     * @param Request $request
     */
    public function storeBefore(Request $request)
    {
        $request->validate([
            // 'appid' => 'required|numeric',
            'os' => 'required|numeric|in:0,1',
            'source' => 'sometimes|alpha_dash',
            'minVer' => [
                'required',
                'version',
                function ($attribute, $value, $fail) use ($request) {
                    if (version_compare($request->minVer, $request->curVer) === 1) {
                        $fail('最低版本号 必须小于或等于 当前版本号');
                    }
                }
            ],
            'curVer' => 'required|version',
            'url' => 'sometimes|url',
            'force' => 'sometimes|in:0,1',
            'comment' => 'sometimes|string',
        ]);
    }

    /**
     * 保存之前
     * @param Request $request
     */
    public function updateBefore(Request $request)
    {
        $request->validate([
            // 'appid' => 'required|numeric',
            'os' => 'required|numeric|in:0,1',
            'source' => 'sometimes|alpha_dash',
            'minVer' => [
                'required',
                'version',
                function ($attribute, $value, $fail) use ($request) {
                    if (version_compare($request->minVer, $request->curVer) === 1) {
                        $fail('最低版本号 必须小于或等于 当前版本号');
                    }
                }
            ],
            'curVer' => 'required|version',
            'url' => 'sometimes|url',
            'force' => 'sometimes|in:0,1',
            'comment' => 'sometimes|string',
        ]);
    }

    /**
     * 批量处理
     * @param Request $request
     * @return Application|ResponseFactory|Response
     */
    public function batch(Request $request)
    {
        $sources = $request->sources;
        foreach ($sources as $source) {
            $url = str_replace(['渠道',], [$source,], $request->url);
            AppVersion::whereSource($source)->updateOrCreate([
                'source' => $source,
            ], [
                'os' => $request->os,
                'minVer' => $request->minVer,
                'curVer' => $request->curVer,
                'url' => $url,
                'force' => $request->force,
                'comment' => $request->comment,
            ]);
        }
        AppVersionCache::reset();
        return responseMessage(__('web.success'));
    }
}
